package expressions;

import exceptions.ParserException;
import parsing.Parser;

/**
 * A syntax element representing some kind of left parenthesis.
 * 
 */
public abstract class LeftParen<T> extends SyntaxElement<T>
{
    public void parse(Parser<T> parser)
    {
        parser.addTopOperator(this);

        while (!(parser.topOperator() instanceof RightParen<?>)
                && parser.getNextToken() != null)
        {
            parser.parseNextToken();
        }

        if (parser.topOperator() == null)
        {
            throw new ParserException();
        }

        int args = 1;

        while (parser.topOperator() != this)
        {
            if (parser.topOperator() instanceof Comma<?>)
                args++;

            parser.buildTopOperator();
        }

        parser.buildTopOperator();

        if (parser.topOperator() instanceof Function<?>)
        {
            Function<T> top = (Function<T>) parser.topOperator();
            top.setArgumentCount(args);
            parser.buildTopOperator();
        }
        else if (args > 1)
        {
            throw new ParserException();
        }
    }
}
